package net.qhzw.vip.qiyu.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.qhzw.vip.qiyu.entity.DtsCarRental;
import net.qhzw.vip.qiyu.entity.RepairCode;
import net.qhzw.vip.qiyu.handler.MyException;
import net.qhzw.vip.qiyu.mapper.DtsCarRentalMapper;
import net.qhzw.vip.qiyu.model.RepairCodeVo;
import net.qhzw.vip.qiyu.result.JsonResult;
import net.qhzw.vip.qiyu.service.DtsCarRentalService;
import net.qhzw.vip.qiyu.service.RepairCodeService;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("sys/repairCode")
@Api(tags = "电瓶车车辆管理")
public class RepairCodeController {

    @Autowired
    private RepairCodeService repairCodeService;

    @Autowired
    private DtsCarRentalMapper dtsCarRentalService;

    @ApiOperation(value = "换车查询")
    @GetMapping("carTransfer/list")
    public JsonResult<List<RepairCode>> carTransferList(@RequestParam Long communityId, @RequestParam Long electricId) {
        List<RepairCode> list = repairCodeService.list(new LambdaQueryWrapper<RepairCode>()
                .eq(RepairCode::getStatus, 1)
                .eq(RepairCode::getVehicleStatus, 1)
                .eq(RepairCode::getVehicleBelongs, communityId)
                .eq(RepairCode::getElectricVehBrandId, electricId));
        return JsonResult.ok(list);
    }

    @ApiOperation(value = "分页查询电动车")
    @GetMapping
    public JsonResult<Map<String, Object>> findByPage(Page<RepairCode> page, String vehicleNumber, Byte vehicleStatus) {
        Long shopId = SecurityUtils.getLoginUser().getShopId();
        PageInfo<RepairCodeVo> repairCodePage = repairCodeService.findByPage(page, vehicleNumber, vehicleStatus, shopId);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("total", (int) repairCodePage.getTotal());
        resultMap.put("records", repairCodePage.getList());
        return JsonResult.ok(resultMap);
    }

    @ApiOperation(value = "根据当前登录用户分页查询电动车")
    @GetMapping("findByUser")
    public JsonResult findPageByUser(Page<RepairCode> page, String vehicleNumber) {
        Long userId = SecurityUtils.getUserId();
        Long shopId = SecurityUtils.getLoginUser().getShopId();
        Page<RepairCode> codePage = repairCodeService.findPageByUser(page, userId, vehicleNumber, shopId);
        return JsonResult.ok(codePage);
    }

    @ApiOperation(value = "查询车辆列表")
    @GetMapping("list")
    public JsonResult<List<RepairCode>> findByPage(Byte vehicleStatus, Byte status, Long vehicleBelongs) {
        Long shopId = SecurityUtils.getLoginUser().getShopId();
        List<RepairCode> repairCodes = repairCodeService
                .list(new LambdaQueryWrapper<RepairCode>()
                        .eq(shopId != 1, RepairCode::getShopId, shopId)
                        .eq(status != null, RepairCode::getStatus, status)
                        .eq(vehicleStatus != null, RepairCode::getVehicleStatus, vehicleStatus)
                        .eq(vehicleBelongs != null, RepairCode::getVehicleBelongs, vehicleBelongs));
        return JsonResult.ok(repairCodes);
    }

    @ApiOperation(value = "根据ID查询产品码表")
    @GetMapping("{id}")
    public JsonResult<RepairCode> findRepairCode(@PathVariable Long id) {
        RepairCode repairCode = repairCodeService.getById(id);
        return JsonResult.ok(repairCode);
    }


    @ApiOperation(value = "添加产品码表")
    @PostMapping
    public JsonResult addRepairCode(@RequestBody RepairCode repairCode) {
        Long shopId = SecurityUtils.getLoginUser().getShopId();
        repairCode.setShopId(shopId);
        RepairCode initDB = initDB(repairCode);
        boolean save = repairCodeService.addRepairCode(initDB);
        if (save) {
            return JsonResult.ok();
        }
        return JsonResult.fail();
    }


    @ApiOperation(value = "修改产品码表")
    @PutMapping
    public JsonResult updateRepairCode(@RequestBody RepairCode repairCode) {
        boolean save = repairCodeService.updateRepairCode(initDB(repairCode));
        if (save) {
            return JsonResult.ok();
        }
        return JsonResult.fail();
    }

    @ApiOperation(value = "修改车辆状态new")
    @PostMapping("updateVehicleStatus")
    public JsonResult updateVehicleStatus(@RequestBody RepairCode repairCode) {
        boolean save = repairCodeService.updateVehicleStatus(initDB(repairCode));
        if (save) {
            return JsonResult.ok();
        }
        return JsonResult.fail();
    }


    @ApiOperation(value = "修改车辆状态")
    @PutMapping("setStatus")
    public JsonResult setStatus(@RequestBody RepairCode repairCode) {
        boolean save = repairCodeService.updateRepairCode(repairCode);
        if (save) {
            return JsonResult.ok();
        }
        return JsonResult.fail();
    }

    @ApiOperation(value = "修复车辆")
    @PutMapping("repairRepairCode/{id}")
    public JsonResult repairRepairCode(@PathVariable Long id) {
        RepairCode repairCode = new RepairCode();
        repairCode.setId(id);
        repairCode.setVehicleStatus((byte) 1);
        boolean update = repairCodeService.updateById(repairCode);
        if (update) {
            return JsonResult.ok();
        }
        return JsonResult.fail();
    }


    @ApiOperation(value = "删除车辆")
    @DeleteMapping("{id}")
    public JsonResult delRepairCode(@PathVariable String id) {
        List<String> list = Arrays.asList(id.split(","));
        List<DtsCarRental> dtsCarRentals = dtsCarRentalService.selectBatchIds(list);
        if (dtsCarRentals.size() > 0){
            return JsonResult.fail("该车已在某个状态使用不允许删除");
        }

        boolean remove = repairCodeService.removeByIds(list);
        if (remove) {
            return JsonResult.ok();
        }
        return JsonResult.fail();
    }


    /***
     * 初始化参数,校验参数
     * @param repairCode
     * @return
     */
    private RepairCode initDB(RepairCode repairCode) {
        int count1 = repairCodeService.count(new LambdaQueryWrapper<RepairCode>().eq(RepairCode::getNumberPlate, repairCode.getNumberPlate()));
        int count2 = repairCodeService.count(new LambdaQueryWrapper<RepairCode>().eq(RepairCode::getFrameNumber, repairCode.getFrameNumber()));
        int count3 = repairCodeService.count(new LambdaQueryWrapper<RepairCode>().eq(RepairCode::getVehicleNumber, repairCode.getVehicleNumber()));
        if (repairCode.getId() == null) {
            if (count1 > 0) {
                throw new MyException("车牌号已存在!");
            }
            if (count2 > 0) {
                throw new MyException("车架号已存在!");
            }
            if (count3 > 0) {
                throw new MyException("电动车编号已存在!");
            }
            repairCode.setId(IdWorker.getId());
            repairCode.setStatus((byte) 1);
            repairCode.setCreated(new Date());
            repairCode.setCreateBy(SecurityUtils.getUserId());
            return repairCode;
        }
        if (count1 > 1) {
            throw new MyException("车牌号已存在!");
        }
        if (count2 > 1) {
            throw new MyException("车架号已存在!");
        }
        if (count3 > 1) {
            throw new MyException("电动车编号已存在!");
        }
        return repairCode;
    }


}
